package com.xxl.job.admin.core.alarm.impl;

import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/***
 *
 * @author wenyao.wu
 * @since 2020/8/6
 */
@Component
public class DingTalkAlarm implements JobAlarm {

    private static Logger logger = LoggerFactory.getLogger(DingTalkAlarm.class);

    private RestTemplate restTemplate = new RestTemplate();

    @Value("${alarm.dingtalk.webhookurl}")
    private String webhookurl;

    @Value("${alarm.dingtalk.activeProfile}")
    private String profile;


    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        logger.info("发送异常提醒");


        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(webhookurl, createMessage(info, jobLog), String.class);
        logger.info("发送异常提醒,返回结果,status:{},body:{}", responseEntity.getStatusCode(), responseEntity.getBody());

        return true;
    }

    private HttpEntity<Map<String, Object>> createMessage(XxlJobInfo info, XxlJobLog jobLog) {
        Map<String, Object> messageJson = new HashMap<>();
        HashMap<String, String> params = new HashMap<>();
        String text = "# %s" +
                "\n- 执行器：%s"+
                "\n- 环境：%s" +
                "\n- 作业ID：%d ";
        String alarmContent = String.format(text,info.getExecutorHandler(), info.getJobDesc(), profile, jobLog.getId());
        params.put("text", alarmContent);
        params.put("title", "定时任务异常");
        //messageJson.put("dinggroup", this.dingGroup);
        messageJson.put("msgtype", "actionCard");
        messageJson.put("actionCard", params);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return new HttpEntity<>(messageJson, headers);
    }
}
